const fs = require('fs');
const path = require('path');
const yaml = require('yaml');
const { program } = require('commander');

// 定义有效的厂商列表
const validManufactures = ['xiaomi', 'hw', 'honor', 'oppo', 'vivo'];

// 配置命令行参数（新增--comment可选参数）
program
  .requiredOption('-n, --name <name>', '项目中文名')
  .requiredOption('-m, --manufacture <manufacture>', `厂商，必须是以下值之一: ${validManufactures.join(', ')}`)
  .requiredOption('-v, --version <version>', '版本号')
  .requiredOption('-b, --before <before>', '更改前体积')
  .requiredOption('-a, --after <after>', '更改后体积')
  .requiredOption('-l, --limit <limit>', '体积限制')
  .option('-c, --comment <comment>', '项目说明和描述（可选）'); // 新增可选参数

// 解析命令行参数
program.parse(process.argv);
const options = program.opts();

// 验证厂商是否有效
if (!validManufactures.includes(options.manufacture)) {
  console.error(`错误：厂商必须是以下值之一: ${validManufactures.join(', ')}`);
  process.exit(1);
}

// 验证体积参数是否为数字
const numericFields = ['before', 'after', 'limit'];
for (const field of numericFields) {
  if (isNaN(Number(options[field]))) {
    console.error(`错误：${field} 必须是数字`);
    process.exit(1);
  }
}

// 创建新记录（新增comment字段）
const newRecord = {
  name: options.name,
  manufacture: options.manufacture,
  version: options.version,
  addtime: Date.now(),
  before: Number(options.before),
  after: Number(options.after),
  limit: Number(options.limit),
  ispassed: Number(options.after) <= Number(options.limit),
  comment: options.comment || '' // 存储comment，默认空字符串
};

// 读取现有记录
const yamlPath = path.join(__dirname, 'compresslist.yaml');
let records = [];

try {
  if (fs.existsSync(yamlPath)) {
    const yamlContent = fs.readFileSync(yamlPath, 'utf8');
    records = yaml.parse(yamlContent) || [];
  }
} catch (error) {
  console.error('读取现有记录时出错：', error.message);
  process.exit(1);
}

// 添加新记录并写入文件
records.push(newRecord);

try {
  const yamlContent = yaml.stringify(records);
  fs.writeFileSync(yamlPath, yamlContent, 'utf8');
  console.log('记录已成功添加！');
} catch (error) {
  console.error('写入记录时出错：', error.message);
  process.exit(1);
}
